package com.bojiu.lawsearch.lawsearch.task;

import com.bojiu.lawsearch.lawsearch.model.Task;
import com.bojiu.lawsearch.lawsearch.service.TaskService;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class TaskInit {

    public static Map<String, String> wechatInfo = new HashMap<>();
    public static Map<String, String> phonecode = new HashMap<>();

    public static String jsTicket = null;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private TaskService taskService;

    @Scheduled(fixedRate = 3600000)
    public void task() {
        log.debug("开始更新数据");
        wechatInfo.clear();
        phonecode.clear();
        Gson gson = new Gson();

        log.debug("开始获取accesstoken");
        ResponseEntity<String> accessEnity = restTemplate.getForEntity("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx8eedf1ad478a9c2c&secret=5683fa77166018b0d3dc677f62145dc4", String.class);
        String access_token = gson.fromJson(accessEnity.getBody(), JsonObject.class).get("access_token").getAsString();
        log.debug("access_token is :{}", access_token);

        log.debug("开始获取accessToken");
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi";
        ResponseEntity<String> forEntity = restTemplate.getForEntity(String.format(url, access_token), String.class);
        String body = forEntity.getBody();
        log.debug("body is :{}",body);
        jsTicket = gson.fromJson(body, JsonObject.class).get("ticket").getAsString();
        log.debug("jsTicket is :{}", jsTicket);
        log.debug("更新数据成功");

    }

    /**
     * 每日凌晨一点开始对超过7日未评价的任务进行自动评价
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void marking() {
        Task taskParams = new Task();
        taskParams.setStatus(5);
        taskParams.setExpireTime(LocalDateTime.now().minusDays(7).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        log.info("查询超过7日未评价的任务");
        List<Task> tasks = taskService.queryList(taskParams);
        tasks.forEach(task -> taskService.marking(task, BigDecimal.valueOf(5)));
    }
}
